package com.letianpai.activity.contacts;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import com.letianpai.R;
import com.letianpai.adapter.contacts.ContactsAdapter;
import com.letianpai.bean.UserContacts;
import com.letianpai.utils.ContactsUtils;
import com.letianpai.view.CharacterParser;
import com.letianpai.view.PinyinComparator;
import com.letianpai.view.SideBar;
import com.letianpai.view.SideBar.OnTouchingLetterChangedListener;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/*
 *
 */
public class ContactsActivity extends Activity {
    ContactsAdapter contactsAdapter;
    private List<UserContacts> arraylist = new ArrayList<UserContacts>();
    boolean flag = true;
    List<UserContacts> newlist = new ArrayList<UserContacts>();
    private SideBar sideBar;
    private TextView dialog;
    //
    public static boolean isUpdate = false;
    SharedPreferences sp;
    Editor editor;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    private GridView gv;
    SharedPreferences sp1;
    private LinearLayout addll, seekll;
    public final int REQUEST_CODE_ADD = 101;

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    sideBar.setVisibility(View.GONE);
                    break;
                case 2:
                    sideBar.setVisibility(View.VISIBLE);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_picture);
        sp = getSharedPreferences("myPref", MODE_WORLD_READABLE);
        editor = sp.edit();
        editor.putString("islogin", "1");
        editor.commit();
        gv = (GridView) findViewById(R.id.listView);
        addll = (LinearLayout) findViewById(R.id.relativeLayout1);
        seekll = (LinearLayout) findViewById(R.id.relativeLayout2);
        addll.setOnClickListener(new Myclick());
        seekll.setOnClickListener(new Myclick());
        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        //配置文件
        SharedPreferences sp = getSharedPreferences("myPref", MODE_WORLD_READABLE);//第一个参数为文件名，第二个为数据操作模式
        Editor editor = sp.edit();
        if (sp.getString("shard", "2").equals("2")) {
            //添加数据
            editor.putString("shard", "0");
            //通讯录字母检索
            editor.putString("sort", "0");
            //聊天消息声音提醒
            editor.putString("remind", "0");
            //通知消息提醒
            editor.putString("notify", "0");
            //默认界面
            editor.putString("interface", "0");
            //保存数据
            editor.commit();
        }

        pinyinComparator = new PinyinComparator();

        sideBar = (SideBar) findViewById(R.id.sidrbar);
        dialog = (TextView) findViewById(R.id.dialog);
        sideBar.setTextView(dialog);

        gv.setOnItemClickListener(new GridViewListener());
        gv.setOnItemLongClickListener(new GridViewLongListener());
        gv.setOnScrollListener(new ScrollListener());
        getContacts();
        sp1 = getSharedPreferences("myPref", MODE_WORLD_READABLE);
        //获取数据后面一个参数表示无返回时的默认值
        String defaultval = "defaultval";
        String name = sp1.getString("sort", defaultval);

        sort(name);

        if (arraylist.size() % 2 == 1) {
            flag = false;
        }
        contactsAdapter = new ContactsAdapter(this, arraylist);
        gv.setAdapter(contactsAdapter);
    }

    private void sort(String name) {
        if ("0".equals(name)) {
            Collections.sort(arraylist, pinyinComparator);
            //设置右侧触摸监听
            sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {
                @Override
                public void onTouchingLetterChanged(String s) {
                    //该字母首次出现的位置
                    int position = contactsAdapter.getPositionForSection(s.charAt(0));
                    if (position != -1) {
                        gv.setSelection(position);
                    }

                }
            });
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("ContactsActivity"); // 统计页面
        MobclickAgent.onResume(this); // 统计时长
        if (contactsAdapter != null && isUpdate) {
            /*getContacts();
            Collections.sort(arraylist, pinyinComparator);
			System.out.println(arraylist.get(0).getName());
			System.out.println(((UserContacts)contactsAdapter.getItem(0)).getName());
			contactsAdapter.notifyDataSetChanged();*/
            getContacts();
            //获取数据后面一个参数表示无返回时的默认值
            String defaultval = "defaultval";
            String name = sp1.getString("sort", defaultval);

            sort(name);

            if (arraylist.size() % 2 == 1) {
                flag = false;
            } else {
                flag = true;
            }
            contactsAdapter = new ContactsAdapter(this, arraylist);
            gv.setAdapter(contactsAdapter);
            isUpdate = false;
        }
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        MobclickAgent.onPageEnd("ContactsActivity"); // 保证 onPageEnd 在onPause
        // 之前调用,因为 onPause 中会保存信息
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_ADD) {
            getContacts();
            //获取数据后面一个参数表示无返回时的默认值
            String defaultval = "defaultval";
            String name = sp1.getString("sort", defaultval);
            sort(name);
            contactsAdapter = new ContactsAdapter(this, arraylist);
            gv.setAdapter(contactsAdapter);
        }
    }

    private void getContacts() {
        newlist = ContactsUtils.getContacts(this);
        arraylist = filledData(newlist);

        for (int i = 0; i < newlist.size(); i++) {
            arraylist.get(i).setNumber(newlist.get(i).getNumber());
            arraylist.get(i).setName(newlist.get(i).getName());
            arraylist.get(i).setPlace(newlist.get(i).getPlace());
            arraylist.get(i).setUserId(newlist.get(i).getUserId());
            arraylist.get(i).setPicture(newlist.get(i).getPicture());

        }

    }

    // 点击事件
    class GridViewListener implements OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {

            if (flag == false) {
                if (position < arraylist.size()) {
                    Intent intent = new Intent(ContactsActivity.this,
                            ContactsInformationActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("id", arraylist.get(position)
                            .getUserId());
                    bundle.putInt("position", position);
                    bundle.putString("name", arraylist.get(position)
                            .getName());
                    if (arraylist.get(position).getPicture() != null) {
                        bundle.putParcelable("head", arraylist.get(position).getPicture());
                    }
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            } else {

                Intent intent = new Intent(ContactsActivity.this,
                        ContactsInformationActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("id", arraylist.get(position).getUserId());
                bundle.putString("name", arraylist.get(position).getName());
                bundle.putParcelable("head", arraylist.get(position).getPicture());
                bundle.putInt("position", position);

                intent.putExtras(bundle);
                startActivity(intent);

            }
        }

    }

    // 长按事件
    class GridViewLongListener implements OnItemLongClickListener {

        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view,
                                       int position, long id) {
            if (flag == false) {
                if (position < arraylist.size()) {
                    String userNumber = arraylist.get(position).getNumber()
                            .get(0);
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
                            + userNumber));
                    ContactsActivity.this.startActivity(intent);
                }
            } else {
                String userNumber = arraylist.get(position).getNumber()
                        .get(0);
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"
                        + userNumber));
                ContactsActivity.this.startActivity(intent);
            }
            return false;
        }

    }

    //点击事件
    class Myclick implements OnClickListener {

        @Override
        public void onClick(View arg0) {
            switch (arg0.getId()) {
                case R.id.relativeLayout1:
                    Intent intent = new Intent(ContactsActivity.this,
                            AddContactsActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_ADD);
                    break;
                case R.id.relativeLayout2:
                    Intent intent2 = new Intent(ContactsActivity.this,
                            SeekContactsActivity.class);
                    startActivity(intent2);
                    break;
                default:
                    break;
            }
        }

    }

    //滑动事件
    class ScrollListener implements OnScrollListener {

        @Override
        public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {

        }

        @Override
        public void onScrollStateChanged(AbsListView arg0, int arg1) {
            if (arg1 == SCROLL_STATE_TOUCH_SCROLL) {
                sideBar.setVisibility(View.VISIBLE);
            }
            if (arg1 == SCROLL_STATE_FLING) {
                sideBar.setVisibility(View.VISIBLE);
            }

            if (arg1 == SCROLL_STATE_IDLE) {

                new Thread() {
                    public void run() {
                        try {
                            sleep(5000);
                            handler.sendEmptyMessage(1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }.start();

            }
        }
    }


    private List<UserContacts> filledData(List<UserContacts> arraylist) {
        List<UserContacts> mSortList = new ArrayList<UserContacts>();
        for (int i = 0; i < arraylist.size(); i++) {
            UserContacts sortModel = new UserContacts();

            //汉字转换成拼音
            String pinyin = characterParser.getSelling(arraylist.get(i).getName());
            String sortString = pinyin.substring(0, 1).toUpperCase();
            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }
            mSortList.add(sortModel);
        }
        return mSortList;
    }

}
